#include <cctype>
#include <algorithm>
#include "Query.hh"

// 读文件按行存到vector中
TextQuery::TextQuery(ifstream& ifs)
    : _lines(new vector<string> ()){

    _lines->reserve(100);
    _lines->push_back("");

    size_t num = 1;
    string line;
    while(getline(ifs,line)){
        _lines->push_back(line);

        string t_line = TextQuery::cleanup_str(line);
        istringstream iss(t_line);
        string word;

        while(iss >> word){
            shared_ptr<set<size_t>>& t = _dict[word];

            if(t == nullptr){
                t.reset(new set<size_t>);
            }
            t->insert(num);
        }
        ++num;
    }
}

// 除去非法字符和统一大小写
string TextQuery::cleanup_str(const string& line){
    string t_line = line;
    for(auto& ch : t_line){
        if(!isalpha(ch)){
            ch = ' ';
            continue;
        }
        if(isupper(ch)){
            tolower(ch);
        }
    }
    return t_line;
}


// 测试是否插入成功
void TextQuery::display_map(){
    for(auto& elem : _dict){
        cout << "单词：" << elem.first;
        cout << "词频：" << elem.second->size();
    }
}


// 返回 word 的查询结果。。。。。未完成
QueryResult TextQuery::query(const string& word) const{

    auto t = _dict.find(word);
    if(t == _dict.end()){
        cout << "没有这个单词" << endl;
        // TODO
        return QueryResult(word, nullptr, _lines);
    }
    return QueryResult(word, t->second, _lines);
}



/*---------------------------------------------------------------------*/

QueryResult::QueryResult(string s, shared_ptr<set<size_t>> p, shared_ptr<vector<string>> f)
        : _word(s)
	    , _lineNum(p)
	    , _lines(f){
}

// 打印得到的结果
ostream& print(ostream& os, const QueryResult& rhs){
    os << "单词出现: " << rhs.size() << "次" << endl;
    for(auto& num : *(rhs._lineNum)){
        cout << "(line" << num << ")" << (*(rhs._lines))[num]<< endl;
    }
    return os;
}


/*---------------------------------------------------------------------*/

using std::set_difference;

QueryResult NotQuery::eval(const TextQuery& txt) const{
    string word = _query.rep();

    QueryResult res = txt.query(word);
    set<size_t> t_set;

    for(size_t i = 1; i <= res.size(); ++i){
        t_set.insert(i);
    }

    set<size_t> res_set;
    set_difference(res.begin(), res.end(), t_set.begin(), t_set.end(), res_set.begin());

    
}









